// 与后端API通信的数据库服务

// 基础API URL
const API_URL = 'http://localhost:3001/api';

// 初始化数据库连接（这里实际上是连接到后端API）
export const initDB = async () => {
    try {
        // 测试API连接
        const response = await fetch(`${API_URL}/questions`);
        if (!response.ok) {
            throw new Error(`无法连接到API: ${response.status} ${response.statusText}`);
        }
        console.log('成功连接到后端API');
        return true; // 返回true表示连接成功
    } catch (error) {
        console.error('初始化API连接失败:', error);
        throw error;
    }
};

// 获取所有题目
export const getAllQuestions = async () => {
    try {
        const response = await fetch(`${API_URL}/questions`);
        if (!response.ok) {
            throw new Error(`获取题目失败: ${response.status} ${response.statusText}`);
        }
        return await response.json();
    } catch (error) {
        console.error('获取题目失败:', error);
        throw error;
    }
};

// 添加新题目
export const addQuestion = async (questionData) => {
    try {
        const response = await fetch(`${API_URL}/questions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(questionData)
        });
        if (!response.ok) {
            throw new Error(`添加题目失败: ${response.status} ${response.statusText}`);
        }
        return await response.json();
    } catch (error) {
        console.error('添加题目失败:', error);
        throw error;
    }
};

// 更新题目
export const updateQuestion = async (id, questionData) => {
    try {
        const response = await fetch(`${API_URL}/questions/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(questionData)
        });
        if (!response.ok) {
            throw new Error(`更新题目失败: ${response.status} ${response.statusText}`);
        }
        return await response.json();
    } catch (error) {
        console.error('更新题目失败:', error);
        throw error;
    }
};

// 删除题目
export const deleteQuestion = async (id) => {
    try {
        const response = await fetch(`${API_URL}/questions/${id}`, {
            method: 'DELETE'
        });
        if (!response.ok) {
            throw new Error(`删除题目失败: ${response.status} ${response.statusText}`);
        }
        return await response.json();
    } catch (error) {
        console.error('删除题目失败:', error);
        throw error;
    }
};

// 不再需要保存数据库到localStorage，因为数据现在存储在服务器上
export const saveDB = () => {
    console.log('数据已保存到服务器，无需本地保存');
    return Promise.resolve();
};